<template>
  <BasicModal
    v-bind="$attrs"
    @register="register"
    :title="'ASIN限制销售 - ' + modelRef.asin"
    @visible-change="handleVisibleChange"
    @ok="confirm_get"
  >
    <div class="pt-3px pr-3px">
      <BasicForm @register="registerForm" :model="modelRef" />
    </div>
  </BasicModal>
</template>
<script lang="ts" setup>
import {nextTick, reactive} from 'vue';
import { BasicModal, useModalInner } from '/@/components/Modal';
import { BasicForm, FormSchema, useForm } from '/@/components/Form';
import {set_asin_limit, getAllLimitType} from "/@/api/demo/task";
import {useMessage} from "/@/hooks/web/useMessage";

const schemas: FormSchema[] = [
  {
    label: '限制类型',
    field: 'limit_type',
    required: true,
    component: 'ApiSelect',
    colProps: { span: 22 },
    componentProps: {
      api: getAllLimitType,
      labelField: 'name',
      valueField: 'value',
    },
  },
  {
    field: 'limit_reason',
    component: 'InputTextArea',
    label: '限制原因',
    colProps: {
      span: 22,
    },
  },
];

const props = defineProps({
  userData: { type: Object },
});
const emit = defineEmits(['reload_data', 'register'])
const { createMessage } = useMessage()
const modelRef = reactive({
  'month': '',
  'asin': '',
  'group_name': '',
  'country_desc': '',
});
const [
  registerForm,
  {
    getFieldsValue,
    resetFields,
    validateFields,
    setFieldsValue
  },
] = useForm({
  labelWidth: 100,
  schemas,
  showActionButtonGroup: false,
  actionColOptions: {
    span: 24,
  },
});

async function validateForm() {
  try {
    await validateFields();
    return true;
  } catch (error) {
    return false;
  }
}

const [register, {closeModal, changeOkLoading, changeLoading}] = useModalInner((data) => {
  data && onDataReceive(data);
});

function onDataReceive(data) {
  modelRef.month = data.month
  modelRef.asin = data.asin
  modelRef.group_name = data.group_name
  modelRef.country_desc = data.country_desc

  if (data.limit_type !== null){
    setFieldsValue({
      'limit_type': data.limit_type,
      'limit_reason': data.limit_reason,
    })
  }else {
    resetFields();
  }
}

async function confirm_get(){
  validateForm().then(result => {
    if (result){
      changeLoading(true);
      changeOkLoading(true);

      var form_data = getFieldsValue();
      form_data.asin = modelRef.asin;
      form_data.month = modelRef.month;
      form_data.group_name = modelRef.group_name;
      form_data.country_desc = modelRef.country_desc;

      set_asin_limit(form_data).then(() => {
        changeLoading(false);
        changeOkLoading(false);
        setTimeout(function (){
          closeModal();
          emit('reload_data')
        }, 500)
      }, () => {
        changeLoading(false);
        changeOkLoading(false);
      })
    }
  }).catch(error => {
    createMessage.error(error)
  })
}

function handleVisibleChange(v) {
  v && props.userData && nextTick(() => onDataReceive(props.userData));
}

</script>
